import logging
from logging.handlers import RotatingFileHandler
import json
from fastapi import Request
from .token_service import TokenService

def setup_logging():
    logger = logging.getLogger("uvicorn.error")
    logger.setLevel(logging.INFO)

    # JSON 格式日志（便于 ELK 分析）
    formatter = logging.Formatter(
        json.dumps({
            "timestamp": "%(asctime)s",
            "level": "%(levelname)s",
            "message": "%(message)s",
            "path": "%(pathname)s",
            "line": "%(lineno)d"
        })
    )

    # 文件日志（按大小滚动）
    file_handler = RotatingFileHandler(
        "app.log", maxBytes=1024*1024, backupCount=5, encoding="utf-8"
    )
    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)

    # 生产环境可添加 Sentry 或 Logstash 集成
    # import sentry_sdk
    # sentry_sdk.init(dsn="your-dsn")

"""
中间件配置，暂时不需要，和其他配置冲突
"""
async def log_request(request: Request, call_next):
    # 配置日志
    logging.basicConfig(
        level=logging.ERROR,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        handlers=[
            logging.FileHandler('app_errors.log'),  # 日志写入文件
            logging.StreamHandler()  # 日志输出到控制台
        ]
    )
    logger = logging.getLogger("uvicorn.error")
    try:
        response = await call_next(request)
        # 检查是否需要刷新令牌
        auth_header = request.headers.get("Authorization")
        if auth_header and auth_header.startswith("Bearer "):
            token = auth_header.split(" ")[1]
            
            if TokenService.should_refresh_token(token):
                new_token = TokenService.refresh_access_token(
                    request.state.refresh_token  # 假设刷新令牌存储在请求上下文中
                )
                response.headers["X-New-Access-Token"] = new_token
            
        logger.info(
            f"Request: {request.method} {request.url} - Status: {response.status_code}"
        )
        return response
    except Exception as e:
        logger.error(
            f"Error: {str(e)}", exc_info=True,
            extra={"path": request.url.path, "method": request.method}
        )
        raise